package com.cold.legendary.mock.context.whole.element;

import com.cold.legendary.mock.proxy.LMockFactoryBean;
import lombok.Data;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cold
 * @since  2021/12/24
 */
@Data
public class WholeMockInjectElement {
    /**
     * 被注入mock的bean
     */
    private Object mockInjectBeanObj;
    /**
     * 需要mock的bean的names
     */
    private List<Class> mockBeanClazzes;


    public void inject() throws Exception {
        List<Field> fieldList = new ArrayList<>();
        ReflectionUtils.doWithFields(mockInjectBeanObj.getClass(), field -> {
            if (mockBeanClazzes.stream().anyMatch(e -> e.getName().equals(field.getType().getName()))) {
                fieldList.add(field);
            }
        });

        for (Field field : fieldList) {
            Class<?> mockBeanClass = field.getType();
            ReflectionUtils.makeAccessible(field);
            Object mockBean = field.get(mockInjectBeanObj);
            LMockFactoryBean mockFactoryBean = new LMockFactoryBean(mockBeanClass.getName(), mockBeanClass, mockInjectBeanObj, mockBean);
            Object proxyMockBean = mockFactoryBean.getObject();
            field.set(mockInjectBeanObj, proxyMockBean);
        }


    }


}
